<template>
	<div id="supplierSettlement">
		<div class="top">
			<div class="title">供应商结算<i></i></div>
		</div>
<!--		<el-alert v-if="slForm.errorMessage &&  slForm.status==='ERROR'" style="margin-bottom: 20px "-->
<!--			:title="slForm.errorMessage" type="error">-->
<!--		</el-alert>-->
		<el-form v-if="slForm" class="slForm" ref="slForm" :model="slForm" :rules="rules" label-position="top"
			v-loading="loading" :element-loading-text="loadingText">
			<el-row :gutter="20">
				<el-col :span="8">
					<el-form-item prop="collectWay">
						<template #label>
							收款方式
							<el-popover placement="right" width="400" trigger="hover">
								<h3>请仔细阅读以下说明</h3>
								<p>如有<span>一次性收款</span>，直接选择“一次性收款并结项”</p>
								<p>如有<span>分三次及三次以上收款</span>，第一次选择“申请首次收款”，第二次选择“申请尾款”</p>
								<p>如有<span>分三次及三次以上收款</span>，第一次选择“申请首次收款”，中间付款选择“申请阶段收款”，最后一笔选择“申请尾款”
								</p>
								<p><span>据实结算</span>的收款方式仅支持费用类型是会议类，框架服务模式，按场次收款的项目，可多次申请</p>
								<i class="el-icon-info" slot="reference"></i>
							</el-popover>
						</template>
						<!-- {{collectWayEnums}} -->
						<el-select  disabled v-model="slForm.collectWay" placeholder="请选择收款方式"
							@change="getProjectConfigFun">
							<el-option v-for="(item,i) in collectWayEnums" :key="i" :label="item.label"
								:value="item.value"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="feeType">
						<template #label>费用类型</template>
						<el-select v-model="slForm.feeType" placeholder="请选择收款方式" disabled>
							<el-option v-for="(item,i) in feeTypeEnums" :key="i" :label="item.label"
								:value="item.value"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="projectName">
						<template #label>项目名称</template>
						<el-input v-model="slForm.projectName" placeholder="请输入项目名称" disabled></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8" v-if="slForm.collectWay=='2' ||slForm.collectWay=='3'">
					<el-form-item>
						<template #label>上阶段收款金额</template>
						<el-input disabled type="number" v-model.number="slForm.lastUsedMoney" placeholder="请完善上阶段结算明细">
							<template slot="append">元</template>
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="applyMoney">
						<template #label>本次收款金额</template>
						<el-input disabled type="number" v-model.number="slForm.applyMoney" placeholder="请完善结算明细">
							<template slot="append">元</template>
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="supplierName">
						<template #label>供应商名称</template>
						<el-input disabled v-model="slForm.supplierName" placeholder="请输入供应商名称"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="feeTypeNo1">
						<template #label>金蝶费用类型</template>
						<el-select
							:disabled="slForm.status=='SUBMIT'||slForm.status=='SUCCESS'||slForm.status=='FINISH'"
							clearable v-model="slForm.feeTypeNo" filterable placeholder="请选择金蝶费用类型">
							<el-option v-for="item in expenseItem" :key="item.expenseItemID" :label="item.expenseItem"
								:value="item.expenseItemID">
							</el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item>
						<template #label>金蝶项目编号</template>
						<el-input :disabled="slForm.status=='SUBMIT'||slForm.status=='SUCCESS'||slForm.status=='FINISH'"
							v-model="slForm.projectNo" placeholder="请输入金蝶项目编号"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="receiptType">
						<template #label>发票类型</template>
						<el-select
							:disabled="slForm.status=='SUBMIT'||slForm.status=='SUCCESS'||slForm.status=='FINISH'"
							v-model="slForm.receiptType" placeholder="请选择收款方式">
							<el-option v-for="(item,i) in receiptTypeEnums" :key="i" :label="item.label"
								:value="item.value"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="deliveryNum">
						<template #label>快递单号</template>
						<el-input :disabled="slForm.status=='SUBMIT'||slForm.status=='SUCCESS'||slForm.status=='FINISH'"
							v-model="slForm.deliveryNum" placeholder="邮寄纸质材料快递单号 (若无不填写)"></el-input>
					</el-form-item>
				</el-col>

        <el-col :span="8">
          <el-form-item prop="deliveryNum">
            <template #label>结算状态</template>
            <el-input disabled  :value=" formatStatus(slForm)"></el-input>
          </el-form-item>
        </el-col>

				<el-col :span="24">
					<el-form-item prop="meetingIds">
						<template #label>本次结算的会议场次</template>
						<el-select v-model="slForm.meetingIds" placeholder="请选择您要结算的会议" clearable multiple
							@change="selectMeetingChange" :collapse-tags="false"
							:disabled="slForm.status=='SUBMIT'||slForm.status=='SUCCESS'||slForm.status=='FINISH'">
							<el-option v-for="item in meetingList" :key="item.id" :label="item.meetingTitle"
								:value=" Number(item.id)">
								{{ item.meetingTitle }} / {{ $moment(item.updateTime).format('lll') }}
							</el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>

<!--      一次性收款并结算      首付款      据实结算 没有山阶段支出明细-->

			<div v-for="(item,meetingIndex) in selectMeetingList " :key="meetingIndex"   >
				<h1 style="font-size: 17px">【{{ item.meetingTitle }}】</h1>
				<el-form-item  v-if="slForm.collectWay==2 || slForm.collectWay==3">
					<template #label>
						<b class="titB"> 上阶段实际支出明细</b>
					</template>
					<el-table :data="item.lastDetailDtos" style="width: 100%">
						<el-table-column label="序号" width="100" type="index" align="center"></el-table-column>
						<el-table-column label="支出明细" align="center">
							<template slot-scope="scope">
								<el-select v-model.async="scope.row.spendingProjectCode" placeholder="请选择收款方式(支持关键字搜索)"
									:disabled="scope.row.spendingProjectCode=='41'||scope.row.spendingProjectCode=='1' ||scope.row.spendingProjectCode=='42' ||scope.row.spendingProjectCode=='39'||scope.row.spendingProjectCode=='40'"
									filterable clearable>
									<el-option v-for="detail in projectTree" :key="detail.id"
										:label="detail.projectType" :value="detail.id.toString()" />
								</el-select>
							</template>
						</el-table-column>
						<el-table-column label="金额(元)" align="center">
							<template slot-scope="scope">
								<el-input type="number" v-model.number="scope.row.money" placeholder="仅支持数字及小数点后2位"
									:min="0" @input="moneyChange(scope.$index,$event,meetingIndex,'L')"
									:disabled="scope.row.spendingProjectCode=='UM000'">
									<template slot="append">元</template>
								</el-input>
							</template>
						</el-table-column>
						<el-table-column width="200" align="center"
							v-if="slForm.status=='SUBMIT'||slForm.status=='SUCCESS'">
							<template slot="header" slot-scope="scope">
								操作
							</template>
							<template slot-scope="scope">
								<el-link @click="goUploadFile(scope.row)"> 去查看</el-link>
							</template>
						</el-table-column>
						<el-table-column width="250" align="center" v-else>
							<template slot="header" slot-scope="scope">
								操作
							</template>
							<template slot-scope="scope">

								<el-button
									v-if="scope.row.spendingProjectCode!='41'&&scope.row.spendingProjectCode!='1'   && slForm && (slForm.status === 'WAIT' || slForm.status === 'ERROR' || !slForm.id)"
									type="text" @click="deleteNewRows(scope.$index,meetingIndex,'L')">删除行
								</el-button>

								<el-button v-if="scope.row.id " type="text" @click="goUploadFile(scope.row)">
									<span v-if=" scope.row.spendingProjectCode=='42'">

									</span>
									<span v-else> {{
                      slForm && (slForm.status === 'WAIT' || slForm.status === 'ERROR' || !slForm.id) ? '去上传文件' : '查看上传文件'
                    }}


                  </span>
								</el-button>

								<span v-else style="color: red;margin-left: 10px;">(请先保存信息后再上传附件)</span>

                <el-tooltip
                    v-if="slForm.status === 'ERROR' && scope.row.rejectFolderMessage"
                    placement="top"
                    effect="dark"
                >
                  <div slot="content">
                    <!--                    <strong>需修改：</strong><br/>-->
                    {{ scope.row.rejectFolderMessage }}
                  </div>
                  <i
                      style="color: #e6a23c; margin-left: 5px; cursor: pointer"
                      class="el-icon-warning"
                  ></i>
                </el-tooltip>



              </template>
						</el-table-column>

					</el-table>
					<div class="subtotal">
						<el-button type="text"
							v-if="slForm && (slForm.status === 'WAIT' || slForm.status === 'ERROR' || !slForm.id)"
							@click="addRows(meetingIndex,'L')">新增行
						</el-button>
					</div>
					<div class="subtotal">合计上阶段结算金额： {{ calculateLastTotal(item) }}元</div>
				</el-form-item>


				<el-form-item>
					<template #label>
						<!--            <span style="font-size: 17px">【{{ item.meetingTitle }}】</span> 本次结算-->
						<b class="titB">本次收款 </b>
					</template>
					<div class="options">
						<div class="first">
							<!-- <el-link @click="downloadTemplate()" type="primary"
                icon="el-icon-download">下载结算单模版</el-link>
              <el-upload :action="`${baseUrl}/sign/live/assistant/getSheetData`"
                :show-file-list="false" multiple :headers="{token:token}"
                :on-success="importTheStatement" :before-upload="beforeUploadFun">
                <el-link type="success" icon="el-icon-upload2">导入结算单</el-link>
              </el-upload>
              <span class="tip">(导入为追加导入 以最新下载的结算单模板为准)</span> -->
						</div>
					</div>
					<el-table :data="item.spendingDetailDtos" style="width: 100%">
						<el-table-column label="序号" width="100" type="index" align="center"></el-table-column>
						<el-table-column label="支出明细" align="center">
							<template slot-scope="scope">
								<el-select v-model.async="scope.row.spendingProjectCode" placeholder="请选择收款方式(支持关键字搜索)"
                           :disabled="isSelectDisabled(scope.row)"
									filterable clearable>
									<el-option v-for="detail in projectTree" :key="detail.id"
										:label="detail.projectType" :value="detail.id.toString()"
                             :disabled="['1', '39', '40', '41'].includes(detail.id.toString())"/>
								</el-select>
							</template>
						</el-table-column>
						<el-table-column label="金额(元)" align="center">
							<template slot-scope="scope">
								<el-input type="number"  v-model.number="scope.row.money" placeholder="仅支持数字及小数点后2位"
									:min="0" @input="moneyChange(scope.$index,$event,meetingIndex,'C')"
                          :disabled="isSelectDisabled(scope.row)"
                >

									<template slot="append">元</template>
								</el-input>
							</template>
						</el-table-column>
						<el-table-column width="200" align="center"
							v-if="slForm.status=='SUBMIT'||slForm.status=='SUCCESS'">
							<template slot="header" slot-scope="scope">
								操作
							</template>
							<template slot-scope="scope">
								<el-link @click="goUploadFile(scope.row)"> 去查看</el-link>
							</template>
						</el-table-column>
						<el-table-column width="250" align="center" v-else>
							<template slot="header" slot-scope="scope">
								操作
							</template>
							<template slot-scope="scope">
								<el-button
									v-if="scope.row.spendingProjectCode!='41'&&scope.row.spendingProjectCode!='1' && scope.row.spendingProjectCode!='39' && slForm && (slForm.status === 'WAIT' || slForm.status === 'ERROR' || !slForm.id)"
									type="text" @click="deleteNewRows(scope.$index,meetingIndex,'C')">删除行
								</el-button>
								<el-button v-if="scope.row.id " type="text" @click="goUploadFile(scope.row)">
									<span v-if=" scope.row.spendingProjectCode=='42'">

									</span>
									<span v-else> {{
                      slForm && (slForm.status === 'WAIT' || slForm.status === 'ERROR' || !slForm.id) ? '去上传文件' : '查看上传文件'
                    }}
                  </span>
                </el-button>


								<span v-else style="color: red;margin-left: 10px;">(请先保存信息后再上传附件)</span>





                <el-tooltip
                    v-if="slForm.status === 'ERROR' && scope.row.rejectFolderMessage"
                    placement="top"
                    effect="dark"
                >
                  <div slot="content">
<!--                    <strong>需修改：</strong><br/>-->
                    {{ scope.row.rejectFolderMessage }}
                  </div>
                  <i
                      style="color: #e6a23c; margin-left: 5px; cursor: pointer"
                      class="el-icon-warning"
                  ></i>
                </el-tooltip>


							</template>
						</el-table-column>

					</el-table>
					<div class="subtotal">
						<el-button type="text"
							v-if="slForm && (slForm.status === 'WAIT' || slForm.status === 'ERROR' || !slForm.id)"
							@click="addRows(meetingIndex,'C')">新增行
						</el-button>
					</div>
					<div class="subtotal">合计本次结算金额： {{ calculateTotal(item) }}元</div>
				</el-form-item>


			</div>

			<el-form-item class="formOptions">
				<el-button type="primary"
					v-if="slForm && (slForm.status === 'WAIT' || slForm.status === 'ERROR' || !slForm.id)"
					@click="saveInformation2('slForm')">保存信息
				</el-button>
				<el-button type="primary" @click="submitForm('slForm')"
					v-if="slForm && (slForm.status === 'WAIT' || slForm.status === 'ERROR' || !slForm.id)"
					:disabled="!slForm.id || newDetail || slForm.status=='FINISH'">提交收款申请
				</el-button>
			</el-form-item>
		</el-form>





    <div class="auditLog">
      <h1>审核日志</h1>
      <el-table :data="logList" border class="">
        <el-table-column prop="createTime" label="审核时间" align="center">
        </el-table-column>
        <el-table-column prop="operatorName" label="审核人" align="center">
        </el-table-column>
        <el-table-column prop="status" label="审核结果" align="center">
          <template #default="scope">
            {{ formatStatus(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="驳回原因" align="center">
          <template #default="scope">
            <div v-if="scope.row.status=='ERROR'">
              {{scope.row.remark}}
            </div>

          </template>
        </el-table-column>
      </el-table>
    </div>



<!--    <el-button @click="handleView(slForm.id)">获取url</el-button>-->
	</div>
</template>

<script>
	// import projectTree from '@/assets/projectTree.json';
	import baseUrl from '@/request/config'
  import md5 from 'js-md5' // 局部MD5引用

  import {
    listOrderLog,
    allSpendFolderList,
    getExpenseItem,
    getOrderById,
    getSpendFolderListByMeetingId,
    orderMeetingList,
    saveOrder,
    submitOrder, fetchSettlementViewUrl
  } from '@/request/api'

	export default {
		name: 'supplierSettlement',
		computed: {
			// 获取根据 collectWay 筛选后的 options
			filteredProjectOptions() {
				console.log("dayin")
				console.log(this.projectTree)
				const collectWay = this.slForm.collectWay;
				if (!collectWay) return [];

				const validStatuses = {
					'0': ['0'],
					'1': ['1'],
					'2': ['2', '3'],
					'3': ['2', '3'],
					'4': ['0']
				} [collectWay];

				// 安全过滤 + 保证 item.id 存在
				return (this.projectTree || []).filter(item => {
					return item && item.id && validStatuses.includes(item.id.toString());
				});
			},

			// 判断该选项是否已被其他行选中
			isOptionDisabled() {
				return (code) => {
					return this.slForm.spendingDetailDtos
						.map(dto => dto.spendingProjectCode)
						.includes(code);
				};
			}
		},
		data() {
			return {
				baseUrl,
        logList:[],
				projectId: '',
				meetingId: '',
				orderId: '',
				selectMeetingList: [], //被选择的会议列表

				slForm: {
					collectWay: '', // 收款方式
					feeType: '', // 费用类型
					projectName: '', // 项目名称
					supplierName: '', // 供应商名称
					applyMoney: 0, // 本次收款金额
					receiptType: '', // 发票类型
					deliveryNum: '', // 快递单号
					spendingDetailDtos: [{
						detailType: "",
						id: "",
						spendingProjectCode: "UM000",
						money: ''
					}], //
					feeTypeNo: '',
					projectNo: ''
				},
				newDetail: false,
				rules: {
					collectWay: [{
						required: true,
						message: '请选择收款方式',
						trigger: 'change'
					}],
					feeType: [{
						required: true,
						message: '请选择费用类型',
						trigger: 'change'
					}],
					projectName: [{
						required: true,
						message: '请输入项目名称',
						trigger: 'change'
					}],
					supplierName: [{
						required: true,
						message: '请输入供应商名称',
						trigger: 'change'
					}],
					applyMoney: [{
						required: true,
						message: '请完善本次收款明细',
						trigger: 'change'
					}],
					lastUsedMoney: [{
						required: true,
						message: '请完善上阶段支出明细',
						trigger: 'change'
					}],
					receiptType: [{
						required: true,
						message: '请选择发票类型',
						trigger: 'change'
					}],
					deliveryNum: [{
						required: false,
						message: '请输入快递单号',
						trigger: 'blur'
					}],
					meetingIds: [{
						required: true,
						message: '请选择您要结算的会议场次',
						trigger: 'change'
					}],
					projectNo: [{
						required: true,
						message: '请输入金蝶项目编号',
						trigger: 'change'
					}],
					feeTypeNo: [{
						required: true,
						message: '请选择金蝶项目类型',
						trigger: 'change'
					}]
				},
				feeTypeEnums: [{
						value: "0",
						label: "会议类"
					},
					{
						value: '1',
						label: "非会议类"
					}
				],
				collectWayEnums: [{
					value: "0",
					label: "一次性收款并结项"
				}, {
					value: "1",
					label: "首次收款"
				}, {
					value: "2",
					label: "阶段收款"
				}, {
					value: "3",
					label: "尾款"
				}, {
					value: "4",
					label: "据实结算"
				}],
				receiptTypeEnums: [{
						value: "0",
						label: "电子发票"
					}, {
						value: "1",
						label: "纸质发票"
					},
					{
						value: "2",
						label: "电子+纸质发票"
					}
				],
				projectTree: [],
				token: '',
				loading: false,
				loadingText: "",
				meetingList: [],
				folderStatus: {
					CREATED: "已创建",
					AI_REVIEW: "预审中",
					AI_REVIEW_ERROR: "预审失败",
					AI_REVIEW_SUCCESS: '预审成功',
					WAIT: '待提交',
					SUBMIT: '待审核',
					ERROR: '审核驳回',
					SUCCESS: "审核通过",
				},
				expenseItem: []
			}

		},
		created() {
      console.log("生命周期开始",this.$route.query)
      if(this.$route.query.sign){
        this.orderId = this.$route.query.orderId;
        console.log(this.orderId);
        // console.log("生命周期开始1")
        // let tokenObj= JSON.stringify({token: this.$route.query.sign});
        // console.log(tokenObj);
        // console.log("生命周期开始2")
        // sessionStorage.setItem('token', tokenObj);
        // sessionStorage.setItem('embed_mode', true);
      }else {
        console.log("生命周期开始3")
        this.projectId = this.$route.query.pId;
        this.meetingId = this.$route.query.mId;
        this.orderId = this.$route.query.orderId ? this.$route.query.orderId : this.slForm.id;
        console.log(this.orderId)
      }


			this.getParams();
			this.getExpenseItemFun();
		},
		methods: {
      //查询审核日志
      loadLog(orderId) {
        if(!orderId){
          return;
        }
        listOrderLog({
          orderId: orderId
        }).then(res => {
          if (res.code == 200) {
            // 只保留 status 为 'ERROR' 的数据
            this.logList = res.data.filter(item => item.status === 'ERROR');
          }
        })
      },

      isSelectDisabled(row){
      // :disabled="scope.row.spendingProjectCode=='41'||scope.row.spendingProjectCode=='1' ||scope.row.spendingProjectCode=='42' ||scope.row.spendingProjectCode=='39'||scope.row.spendingProjectCode=='40'"

        // 条件1：特定 spendingProjectCode 值 → 禁用
        const isSpecialCode = ['1', '39', '40', '41', '42'].includes(row.spendingProjectCode);

        if (isSpecialCode) {
          return true;
        }

        // 条件2：只有在以下情况才允许编辑（即：其他情况禁用）
        const canEdit =
            !this.slForm.id ||
            this.slForm.status === 'WAIT' ||
            this.slForm.status === 'ERROR';

        // 返回：不能编辑时禁用
        return !canEdit;
      },


      /**
       * 查看结算单 - 生成安全查看链接
       */
       handleView(orderId) {
        console.log(orderId)
        try {
          // 2. 生成时间戳
          const timestamp = Date.now().toString();

          // 3. 生成签名：MD5(orderId + timestamp + secretKey)
          const secretKey = 'wmzh'; // 抽到 config.js

          const sign = md5(orderId  + timestamp + secretKey);
          // 4. 请求后端获取查看链接
          const params = { orderId, timestamp, sign };
          fetchSettlementViewUrl(params).then(res => {
            const viewUrl = res.data;
            // 5. 在新标签页打开
            window.open(viewUrl, '_blank');
          })
        } catch (error) {
          this.$message({
            type: 'error',
            message: '获取结算单链接失败，请稍后重试!'
          })
        }

      },


			// 计算总金额
			calculateTotal(meeting) {
				const money = meeting.spendingDetailDtos.reduce((sum, item) => {
					const money = parseFloat(item.money);
					return sum + (isNaN(money) ? 0 : money);
				}, 0).toFixed(2);

				return money
			},

			// 计算总金额
			calculateLastTotal(meeting) {
				const money = meeting.lastDetailDtos.reduce((sum, item) => {
					const money = parseFloat(item.money);
					return sum + (isNaN(money) ? 0 : money);
				}, 0).toFixed(2);

				// this.slForm.applyMoney=money
				return money
			},


			// 删除某一行
			deleteNewRows(detailIndex, meetingIndex, detailType) {
				const meeting = this.selectMeetingList[meetingIndex];

				// 确定删除的是哪个列表
				const listKey = detailType === 'L' ? 'lastDetailDtos' : 'spendingDetailDtos';
				// 删除对应列表中的某一行
				meeting[listKey].splice(detailIndex, 1);

				// 重新计算总金额 applyMoney
				this.calculateTotalApplyMoney();

			},
			// 增加行
			addRows(meetingIndex, detailType) {
				const meeting = this.selectMeetingList[meetingIndex];
				// 确定添加的是哪个列表
				const listKey = detailType === 'L' ? 'lastDetailDtos' : 'spendingDetailDtos';
				// 添加对应列表中的某一行
				meeting[listKey].push({
					"id": null,
					"supplierApplyCollectId": null,
					"spendingProjectCode": null,
					"money": 0,
					"detailType": detailType,
					"meetingType": null,
					"isDel": null,
					"oldId": null,
					"meetingId": null,
					"createTime": null,
					"updateTime": null
				});
			},

			moneyChange(index, event, meetingIndex, detailType) {
				if (event) {
					const meeting = this.selectMeetingList[meetingIndex];
					// 确定添加的是哪个列表
					const listKey = detailType === 'L' ? 'lastDetailDtos' : 'spendingDetailDtos';
					meeting[listKey][index].money = event.replace(
						/^(\-)*(\d+)\.(\d{0,2}).*$/, '$1$2.$3');
					// this.selectMeetingList[meetingIndex].spendingDetailDtos[index].money = event.replace(
					//     /^(\-)*(\d+)\.(\d{0,2}).*$/, '$1$2.$3');
				}

				// 重新计算总金额 applyMoney
				this.calculateTotalApplyMoney();


			},

			calculateTotalApplyMoney() {
				let totalMoney = 0;
				let lastUsedMoney = 0;

				this.selectMeetingList.forEach(meeting => {
					lastUsedMoney += meeting.lastDetailDtos.reduce((sum, item) => sum + (Number(item.money) || 0),
						0);
					totalMoney += meeting.spendingDetailDtos.reduce((sum, item) => sum + (Number(item.money) || 0),
						0);
				});
				this.slForm.lastUsedMoney = lastUsedMoney
				this.slForm.applyMoney = totalMoney;
			},

			//选择会议
			selectMeetingChange(meetingIds) {
				console.log(meetingIds)
				if (meetingIds.length == 0) {
					return;
				}
				getSpendFolderListByMeetingId({
					meetingIds,
					collectWay: this.slForm.collectWay
				}).then(res => {
					console.log(res)
					if (res.code == 200) {
						// this.selectMeetingList = res.data;
						this.selectMeetingList = this.processMeetingList(res.data)
					}
				})
			},


			getExpenseItemFun(itemName) {
				let data = {}
				data.current = 1;
				data.size = 3000;
				if (itemName) data.itemName = itemName
				getExpenseItem(data).then(res => {
					if (res.code == 200) {
						this.expenseItem = res.data.data
					}
				})
			},
			// 获取会议列表
			getMeetingList() {
				let data = {
					orderId: this.orderId ? this.orderId : this.slForm.id,
					projectId: this.projectId,
					meetingId: this.meetingId,
				};
				orderMeetingList(data).then(res => {
					if (res.code == 200) this.meetingList = res.data;
				});
			},
			// 获取结算单信息
			getSheetDataFun() {
				getOrderById({
					projectId: this.projectId,
					meetingId: this.meetingId,
					orderId: this.$route.query.orderId ? this.$route.query.orderId : this.slForm.id,
					collectWay: this.$route.query.collectWay,
					feeType: this.$route.query.feeType
				}).then(res => {
					if (res.code == 200) {
						let resData = JSON.parse(JSON.stringify(res.data));
						// for (let i in resData) {
						// 	if (resData[i] == null) resData[i] = '';
						// };
						// 确保 meetingIds 是一个数组
						resData.meetingIds = Array.isArray(resData.meetingIds) ? resData.meetingIds : [];
            this.slForm = {
              ...resData,
              lastUsedMoney: resData.lastUsedMoney ?? 0,
              applyMoney: resData.applyMoney ?? 0
            };
						// this.selectMeetingList = res.data.selectMeetingList;
						this.selectMeetingList = this.processMeetingList(res.data.selectMeetingList)
						// this.$forceUpdate()
						this.getMeetingList();
            this.loadLog(this.slForm.id);
					};
				});
			},


			// 近入页面获取必要参数
			getParams() {
				if (this.$route.query.collectWay) {
					this.slForm.collectWay = this.$route.query.collectWay;
				};
				this.getSheetDataFun();
				this.getProjectConfigFun();
				// this.getMeetingList();

			},
			// 获取支出明细类型列表
			getProjectConfigFun() {
				allSpendFolderList().then(res => {
					if (res.code == 200) {
						this.projectTree = res.data
					}
				})


				// getProjectConfig().then(res => {
				// 	if (res.code == 200) {
				// 		this.projectTree = res.data
				// 	}
				// })
			},


			/**
			 * 处理会议列表，将每个会议的结算明细按 detailType 分离为上次和本次结算
			 * @param {Array} meetingList - 原始会议列表
			 * @returns {Array} - 处理后的会议列表，包含 lastDetailDtos 和 currentDetailDtos
			 */
			processMeetingList(meetingList) {
				return meetingList.map(meeting => {
					const lastDetailDtos = [];
					const spendingDetailDtos = [];

					if (Array.isArray(meeting.spendingDetailDtos)) {
						meeting.spendingDetailDtos.forEach(detail => {
							if (detail.detailType === 'L') {
								lastDetailDtos.push(detail);
							} else if (detail.detailType === 'C') {
								spendingDetailDtos.push(detail);
							}
						});
					}

					return {
						...meeting,
						lastDetailDtos,
						spendingDetailDtos
					};
				});
			},

			// 导入结算单前
			beforeUploadFun() {
				if (!this.slForm.collectWay) {
					this.$message.error('请先选择收款方式');
					return false;
				};
			},
			// 导入结算单
			importTheStatement(res) {
				if (res.code == 200) {
					this.$message.success('导入成功')
					for (let n in res.data) {
						let nVal = res.data[n];
						// console.log(inData)
						if (this.slForm.lastDetail) {
							nVal.detailType = "L";
							let inData = this.slForm.lastDetail.map(code => code.spendingProjectCode).indexOf(nVal
								.spendingProjectCode);
							if (inData != -1) {
								this.slForm.lastDetail[inData] = nVal;
							} else {
								this.slForm.lastDetail.push(nVal);
							};
						} else {
							nVal.detailType = "C";
							let inData = this.slForm.spendingDetailDtos.map(code => code.spendingProjectCode).indexOf(nVal
								.spendingProjectCode);
							if (inData != -1) {
								this.slForm.spendingDetailDtos[inData] = nVal;
							} else {
								this.slForm.spendingDetailDtos.push(nVal);
							};
						};
					};
					// console.log(JSON.parse(JSON.stringify(this.slForm)))
					this.$forceUpdate();
				};
			},
			// 去上传文件
			goUploadFile(row) {
				// console.log(JSON.parse(JSON.stringify(row)))
				if (row.spendingProjectCode) {
					this.$router.push({
						name: 'fileListPreview',
						query: {
							id: row.id,
							oId: this.slForm.id,
							pId: this.$route.query.pId,
							isView: this.slForm.isView ? this.slForm.isView : ''
						}
					});
				};
			},


			// 金额变化
			lastMoneyChange(index, event) {
				if (event) {
					this.slForm.lastDetail[index].money = event.replace(
						/^(\-)*(\d+)\.(\d{0,2}).*$/, '$1$2.$3');
				};
				let money = 0;
				this.slForm.lastDetail.map(item => {
					money += Number(item.money); //> 0 ? Number(item.money) : 0;
				});
				this.slForm.lastUsedMoney = money;
			},

			// 提交表单
			submitForm(formName) {
				let formType = true;
				let data = JSON.parse(JSON.stringify(this.slForm));
				if (data.lastDetail) {
					data.spendingDetailDtos = [...data.spendingDetailDtos, ...data.lastDetail];
					delete data.lastDetail;
				};
				for (let i in data.spendingDetailDtos) {
					if (!data.spendingDetailDtos[i].spendingProjectCode) {
						this.$alert('请完善所有的支出明细类型', '提示', {
							confirmButtonText: '确定',
							center: true,
							type: "warning"
						});
						formType = false;
						return false;
					} else if (!data.spendingDetailDtos[i].money && data.spendingDetailDtos[i]
						.spendingProjectCode != 'UM000') {
						this.$alert('请填写所有支出明细类型的金额', '提示', {
							confirmButtonText: '确定',
							center: true,
							type: "warning"
						});
						formType = false;
						return false;
					};
				};
				this.$refs[formName].validate(valid => {
					if (!valid) {
						formType = fasle;
						return false;
					}
				});
				this.loadingText = '正在提交···'
				this.loading = true;
				setTimeout(() => {
					console.log(this.slForm.status)
					delete this.slForm.spendingDetailDtos
					submitOrder({
						orderId: this.slForm.id
					}).then(res => {
						this.loading = false;
						if (res.code == 200) {
							console.log(res.data)
							this.$router.replace({
								query: {
									...this.$route.query,
									orderId: res.data
								}
							});
							this.$message({
								message: '提交成功',
								type: 'success'
							});
							this.getSheetDataFun();
						} else {
							this.$message({
								message: res.msg,
								type: 'error'
							});
						}
					})
				}, 1000);
			},

			saveInformation2(formName) {
				this.$refs[formName].validate(valid => {
					if (!valid) {
						this.$message.warning('请完善表单信息');
						return false;
					}
					this.loadingText = '正在保存···'
					this.loading = true;
					// 深拷贝 slForm 数据
					const data = JSON.parse(JSON.stringify(this.slForm));
					try {
						// 校验明细数据
						if (!this.validateMeetingDetails()) {
							this.loading = false;
							return false;
						}


						// ========== 新增：合并 lastDetailDtos 到 spendingDetailDtos ==========
						const mergedMeetingList = this.selectMeetingList.map(meeting => {
							const spendingDetails = meeting.spendingDetailDtos || [];
							const lastDetails = meeting.lastDetailDtos || [];

							// 合并两个数组
							const mergedDetails = [...spendingDetails, ...lastDetails];

							// 返回新的对象，避免直接修改原始数据（可选）
							return {
								...meeting,
								spendingDetailDtos: mergedDetails,
								// 如果需要，可以清空 lastDetailDtos
								lastDetailDtos: []
							};
						});

						// ========== 提交数据到后端 ==========
						data.selectMeetingList = mergedMeetingList;


						// 提交数据到后端
						// data.selectMeetingList = this.selectMeetingList;
						saveOrder(data).then(res => {
							if (res.code === 200) {
								this.$router.replace({
									query: {
										...this.$route.query,
										orderId: res.data.id
									}
								});
								this.loading = false;
								this.newDetail = false;
								this.$message.success('保存成功');
								this.getSheetDataFun();
							} else {
								this.loading = false;
								this.$message.error(res.msg || '保存失败');
							}
						}).catch(() => {
							this.loading = false;
							this.$message.error('保存失败，请重试');
						});

					} catch (error) {
						this.loading = false;
						this.$message.error('发生异常，请检查输入内容');
						console.error(error);
					}
				});


			},

			validateMeetingDetails() {
				for (let i = 0; i < this.selectMeetingList.length; i++) {
					const meeting = this.selectMeetingList[i];
					const details = meeting.spendingDetailDtos || [];
					const lastDetails = meeting.lastDetailDtos || []; // 获取 lastDetailDtos

					// 校验 spendingDetailDtos
					for (let j = 0; j < details.length; j++) {
						const item = details[j];

						if (!item.spendingProjectCode) {
							this.$alert(`会议【${meeting.meetingTitle}】第${j + 1}行支出类型未选择`, '提示', {
								confirmButtonText: '确定',
								center: true,
								type: 'warning'
							});
							return false;
						}

						if (item.money === null || item.money === '' || item.money === undefined) {
							this.$alert(`会议【${meeting.meetingTitle}】第${j + 1}行金额未填写`, '提示', {
								confirmButtonText: '确定',
								center: true,
								type: 'warning'
							});
							return false;
						}
					}

					// 校验 lastDetailDtos（仅当数组非空时）
					if (Array.isArray(lastDetails) && lastDetails.length > 0) {
						for (let k = 0; k < lastDetails.length; k++) {
							const item = lastDetails[k];

							if (!item.spendingProjectCode) {
								this.$alert(`会议【${meeting.meetingTitle}】历史明细第${k + 1}行支出类型未选择`, '提示', {
									confirmButtonText: '确定',
									center: true,
									type: 'warning'
								});
								return false;
							}

							if (item.money === null || item.money === '' || item.money === undefined) {
								this.$alert(`会议【${meeting.meetingTitle}】历史明细第${k + 1}行金额未填写`, '提示', {
									confirmButtonText: '确定',
									center: true,
									type: 'warning'
								});
								return false;
							}
						}
					}
				}

				return true; // 所有校验通过
			},

      formatStatus(item) {
        const status = item.status
        const statusMap = {
          WAIT:'未提交',
          AI_REVIEW_SUCCESS:'官员审核中',
          OFFICIAL_EXAMINE: '官员审核中',
          SUBMIT: '财务审核中',
          ERROR: '审核驳回',
          SUCCESS: '财务审核通过'
        };
        if (item.operatorId == '0' && status == 'ERROR') {
          return "财务审核驳回"
        }
        return statusMap[status] || '未知状态';
      },


			// 下载结算单模板
			downloadTemplate() {
				let downLodUrl =
					'http://life-oasis.oss-cn-beijing.aliyuncs.com/sign/2024/08/28/ce3c58589fc14b65beed5934f8d27898.xlsx';
				let name = '结算单模板.xlsx';
				const x = new XMLHttpRequest();
				x.open("GET", downLodUrl, true);
				x.responseType = 'blob';
				x.onload = function(e) {
					const url = window.URL.createObjectURL(x.response);
					const a = document.createElement('a');
					a.href = url;
					a.target = '_blank';
					a.download = name;
					a.click();
					a.remove();
				};
				x.send();
			}
		}
	}
</script>

<style lang="scss" scoped>
	#supplierSettlement {
		width: 100%;
		height: 100%;
		padding: 20px;

		.top {
			padding: 20px;
			margin-bottom: 20px;
			border-radius: 20px;
			box-shadow: 0 2px 18px rgba(203, 203, 203, 0.31);

			.title {
				font-size: 20px;
				padding: 0 20px 0 30px;
				position: relative;

				i {
					top: 50%;
					left: 0px;
					width: 20px;
					height: 20px;
					position: absolute;
					border-radius: 50%;
					background-color: #3563E9;
					border: 5px solid #C2D0F8;
					transform: translateY(-50%);
				}
			}

			.searth {
				display: flex;
				margin-top: 20px;

				.el-form-item {
					display: flex;
					align-items: center;
					margin-right: 20px;

					.el-form-item__content {
						flex: 1;
					}
				}
			}
		}

		::v-deep .slForm {
			padding: 20px;
			border-radius: 20px;
			box-shadow: 0 2px 18px rgba(203, 203, 203, 0.31);

			.el-select {
				width: 100%;
			}

			.el-form-item__label {
				padding: 0;
			}

			.titB {
				color: #409EFF;
			}

			.options {
				display: flex;
				align-items: center;

				.first {
					flex: 1;
					margin-right: 30px;
					display: flex;
					align-items: center;

					.el-link {
						margin-right: 20px;
					}
				}
			}

			.subtotal {
				border-bottom: 1px solid #EBEEF5;
				padding: 10px 20px;
				display: flex;
				justify-content: center;
				font-size: 16px;
			}

			.formOptions {
				.el-form-item__content {
					display: flex;
					justify-content: center;

					.el-button {
						margin: 0 20px;
					}
				}
			}
		}
	}

	.el-popover {
		h3 {
			font-size: 16px;
			font-weight: bold;
			margin-bottom: 10px;
		}

		p {
			font-size: 14px;

			span {
				color: red;
			}
		}
	}


  .auditLog {
    margin: 40px;
    margin-top: 10px;
    padding: 40px;
    box-shadow: 0 2px 18px rgba(190, 190, 190, 0.31);
    border-radius: 4px;

    h1 {
      margin-bottom: 20px;
      font-size: 20px;
    }
  }






</style>